package com.cskaoyan.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(Integer[].class)
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]> {
    ObjectMapper objectMapper = new ObjectMapper();
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, Integer[] integers, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(integers);
        preparedStatement.setString(index,value);
    }
    @SneakyThrows
    @Override
    public Integer[] getResult(ResultSet resultSet, String columnLabel) throws SQLException {
        String string = resultSet.getString(columnLabel);
        Integer[] integers = objectMapper.readValue(string, Integer[].class);
        return integers;
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, int i) throws SQLException {
        return new Integer[0];
    }

    @Override
    public Integer[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        return new Integer[0];
    }
}
